package com.powernode.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.ManagerConstants;
import com.powernode.domain.SysMenu;
import com.powernode.ex.handler.BusinessException;
import com.powernode.mapper.SysMenuMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName SysMenuService
 * @Description 系统菜单service
 * @Date 2024/07/21 20:14
 */
@Service
@CacheConfig(cacheNames = "com.powernode.service.SysMenuService")
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {

    @Resource
    private SysMenuMapper sysMenuMapper;

    /**
     * 根据用户id查询用户菜单列表
     *
     * @param loginUserId 用户id
     * @return 用户菜单列表
     */
    @Cacheable(key = "#loginUserId")
    public Set<SysMenu> queryUserMenuListByUserId(Long loginUserId) {
        Set<SysMenu> sysMenus = sysMenuMapper.queryUserMenuListByUserId(loginUserId);
        // 递归处理，树结构
        return transformTree(sysMenus, 0L);
    }

    /**
     * 将菜单列表转换为树结构
     * @param sysMenus 集合
     * @param pId      父级id
     * @return 结果
     */
    private Set<SysMenu> transformTree(Set<SysMenu> sysMenus, long pId) {
        Set<SysMenu> roots = sysMenus.stream().filter(sysMenu -> sysMenu.getParentId().equals(pId)).collect(Collectors.toSet());
        roots.forEach(sysMenu -> sysMenu.setList(transformTree(sysMenus, sysMenu.getMenuId())));
        return roots;
    }

    /**
     * 查询所有菜单权限列表
     * @return 菜单权限列表
     */
    @Cacheable(key = ManagerConstants.SYS_ALL_MENU_KEY)
    public List<SysMenu> queryAllSysMenuList() {
        return sysMenuMapper.selectList(null);
    }

    /**
     * 删除权限
     * @param id 权限id
     * @return 返回删除结果
     */
    @Override
    @CacheEvict(allEntries = true)
    public boolean removeById(Serializable id) {
        // 查询当前权限节点的子节点
        List<SysMenu> childMenuList = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getParentId, id)
        );
        // 判断是否包含子节点
        if (CollectionUtil.isNotEmpty(childMenuList)) {
            throw new BusinessException("当前节点包含子节点，不可删除");
        }
        return super.removeById(id);
    }
}
